package com.jt.auth.config;


import com.jt.auth.service.UserDetailsServiceImpl;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.*;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.Arrays;

/**
 * 在这个对象中负责将所有的认证和授权配置进行整合
 * 1、SpringSecurity(提供认证和授权的实现)
 * 2、TokenConfig(提供了令牌的生成，存储，校验)
 * 3、Oauth2(定义了一套认证规范)*/
@AllArgsConstructor
@Configuration
@EnableAuthorizationServer
public class OAuth2Config
        extends AuthorizationServerConfigurerAdapter {

    //此对象负责完成认证管理
    private AuthenticationManager authenticationManager;
    //TokenStore负责完成令牌创建,信息读取
    private TokenStore tokenStore;
    //JWT令牌转换器(基于用户信息构建令牌,解析令牌)
    private JwtAccessTokenConverter jwtAccessTokenConverter;
    //密码加密匹配器对象
    private PasswordEncoder passwordEncoder;
    //负责获取用户信息信息
    private UserDetailsService userDetailsService;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        /**
         * 由谁完成认证
         * 谁负责访问数据库
         * 支持对什么请求进行认证（默认支持POST）
         * 认证成功后令牌如何生成和存储(默认令牌是UUID.randomUUID(),并且存储方式为内存)*/
        endpoints
                //配置认证管理器
                .authenticationManager(authenticationManager)
                //验证用户的方法获得用户详情
                .userDetailsService(userDetailsService)
                //要求提交认证使用post请求方式,提高安全性
                .allowedTokenEndpointRequestMethods(HttpMethod.POST, HttpMethod.GET)
                //要配置令牌的生成,由于令牌生成比较复杂,下面有方法实现
                .tokenServices(tokenServices());//这个不配置,默认令牌为UUID.randomUUID().toString()

    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security)
            throws Exception {
       // super.configure(security);
        security.tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()")
                .allowFormAuthenticationForClients();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//        super.configure(clients);
        clients.inMemory()
                //定义客户端的ID
                .withClient("gateway-client")
                //定义客户端秘钥（客户端提交用户信息时要携带这个秘钥）
                .secret(passwordEncoder.encode("123456"))
                //定义作用域范围（所有符合规则的客户端）
                .scopes("all")
                //允许客户端基于密码方式，刷新令牌方式实现认证
                .authorizedGrantTypes("password","refresh_token");
    }

    @Bean
    public AuthorizationServerTokenServices tokenServices(){
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(tokenStore);
        tokenServices.setSupportRefreshToken(true);
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter));
        tokenServices.setTokenEnhancer(tokenEnhancerChain);
        tokenServices.setAccessTokenValiditySeconds(3600);//1小时
        //刷新令牌应用场景：一般在用户登录系统后，令牌快过期时，系统自动帮助用户刷新令牌，提高用户的体验感
        tokenServices.setRefreshTokenValiditySeconds(3600*72);//3天
        return tokenServices;
    }

}
